package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.FlavorsMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishFlavorsVO;
import com.sky.vo.DishVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private FlavorsMapper flavorsMapper;

    /*
     * 新增菜品
     * */
    @Override
    public void saveDish(DishDTO dishDTO) {
        dishMapper.saveDish(dishDTO);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(!CollectionUtils.isEmpty(flavors)){

            flavors.forEach(flavor->flavor.setDishId(dishDTO.getId()));
        }
        flavorsMapper.saveFlavors(flavors);
    }

    /*
     * 修改菜品
     * */
    @Override
    public void putDish(DishDTO dishDTO) {
        dishMapper.putDish(dishDTO);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        flavorsMapper.deleteById(dishDTO.getId());
        if(!CollectionUtils.isEmpty(flavors)){
            flavors.forEach(flavor->flavor.setDishId(dishDTO.getId()));
        }
        flavorsMapper.saveFlavors(flavors);
    }

    /*
     * 根据分类id查询菜品
     * */
    @Override
    public Dish selectCategoryId(Long categoryId) {
       Dish dish= dishMapper.selectCategoryId(categoryId);
        return dish;
    }

    /*
     * 删除多个菜品
     * */
    @Override
    public void delectDishByIds(List<Long> ids) {
        dishMapper.delectDishByIds(ids);
    }

    /*
     * 分页条件查询
     * */
    @Override
    public PageResult pageDish(DishPageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<DishVO> dishPage= dishMapper.pageDish(pageQueryDTO);
        return new PageResult(dishPage.getTotal(),dishPage.getResult());
    }

    @Override
    public DishFlavorsVO selectDishWithFlavor(Long id) {
        DishFlavorsVO dishVO= dishMapper.selectDishWithFlavor(id);
        return dishVO;
    }
}
